<?php

namespace app\index\controller;

use addons\wechat\model\WechatCaptcha;
use app\common\controller\Frontend;
use app\common\library\Ems;
use app\common\library\Sms;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Session;
use think\Validate;
use think\Db;

use app\common\model\ReserveSetting;

/**
 * 图片馆申请
 */
class Book extends Frontend
{

    protected $noNeedLogin = ['register', 'into', 'leave'];
    protected $noNeedRight = ['*'];
    protected $layout = 'weiui';

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        // if (!Config::get('fastadmin.usercenter')) {
        //     $this->error(__('User center already closed'));
        // }

        //监听注册登录注销的事件
        // Hook::add('user_login_successed', function ($user) use ($auth) {
        //     $expire = input('post.keeplogin') ? 30 * 86400 : 0;
        //     Cookie::set('uid', $user->id, $expire);
        //     Cookie::set('token', $auth->getToken(), $expire);
        // });
        // Hook::add('user_register_successed', function ($user) use ($auth) {
        //     Cookie::set('uid', $user->id);
        //     Cookie::set('token', $auth->getToken());
        // });
        // Hook::add('user_delete_successed', function ($user) use ($auth) {
        //     Cookie::delete('uid');
        //     Cookie::delete('token');
        // });
        // Hook::add('user_logout_successed', function ($user) use ($auth) {
        //     Cookie::delete('uid');
        //     Cookie::delete('token');
        // });
    }

    /**
     * 空的请求
     * @param $name
     * @return mixed
     */
    public function _empty($name)
    {
        $data = Hook::listen("user_request_empty", $name);
        foreach ($data as $index => $datum) {
            $this->view->assign($datum);
        }
        return $this->view->fetch('user/' . $name);
    }

    /**
     * 预约登记
     */
    public function register()
    {
        //获取预约总数，剩余数量
        $id = 1;
        $row = ReserveSetting::get($id);
        

        $this->assign('pageTitle','图书馆登记');
        $url = $this->request->request('url', '');
        if ($this->request->isPost()) {

            $username = $this->request->post('username');
            $sid = $this->request->post('sid');

            $rule = [
                'username'  => 'require|length:2,20',
                'sid'  => 'require|length:8,30',
            ];

            $msg = [
                'username.require'  => 'Username can not be empty',
                'username.length'   => 'Username must be 2 to 20 characters',
                'sid.require' => 'sid can not be empty',
                'sid.length'  => 'sid must be 8 to 30 characters',
            ];
            $data = [
                'username'  => $username,
                'sid'  => $sid,
            ];
    

            //获取开始预约时间，和结束预约时间
            $begin_time= Config::get('site.begin_time');//开始时间
            $begin_fen= Config::get('site.begin_fen');//开始分钟

            $begin_times = strtotime($begin_time.':'.$begin_fen);
            // echo $begin_times."###<br/>";

            $end_time= Config::get('site.end_time');//结束时间
            $end_fen= Config::get('site.end_fen');//结束分钟

            $end_times = strtotime($end_time.':'.$end_fen);
            //echo $end_times."###<br/>";

            //获取当前的时分
            $local_time = strtotime(date("H:i"));
            //echo $local_time."<br/>"; // 17:16

            if($local_time<$begin_times||$local_time>$end_times)
            {
                $this->error(__('Appointment time not reached'));
            }
            
            ////判断预约数量是否为0
            //预约已满请稍候再试
            if($row['reserved_number']==0){
                $this->error(__('The number of bookings in the library is full'));
            }

            $result = $this->auth->enter($username,$sid);
            if ($result) {

                $where_['nickname']= $username;
                $where_['sid']=$sid;

                $info= Db::name('reserve_record')->where($where_)->find();
                //
                $where['id'] = 1;
                $row = \app\common\model\ReserveSetting::where($where)->find();

                if(empty($row['reserved_number'])){
                    $params['reserved_number'] = $row['reserve_number']-1;
                }else{
                    $params['reserved_number'] = $row['reserved_number']-1;
                }
                $params['add_time'] = time();
                Db::name('reserve_setting')->where($where)->update($params);
                //$res = $this->model->save($params);

                //echo $result."###";exit();
                //从site.php 文件中获取
                $times= Config::get('site.time');
                // $this->success(__('Sign up successful'), $url ? $url : url('user/index'));
                $add_time= date('Y-m-d H:i:s',$info['add_time']);
                $data['times'] = $times;
                $data['add_time']= $add_time;
                $this->success(__('预约成功'), $url ? $url : url('user/index'),$data);                
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        $this->view->assign('row',$row);
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Register'));
        return $this->view->fetch();
    }

    /**
     * 进入图书馆
     *
     * @param string $username  账号
     * @param string $sid 学号
     */    
    public function into()
    { 
        $this->assign('pageTitle','图书馆登记'); 
        if ($this->request->isPost())
        {
            $username = $this->request->post('username');
            $sid = $this->request->post('sid');

            $where['nickname'] = $username;
            $where['sid'] = $sid;
            $where['into_states'] = 0;
            $row = \app\common\model\ReserveRecord::where($where)->find();
            if($row['states']==1){
                //处理进入状态
                $params['into_time']= time();
                $params['into_states']=1;
                $row->save($params);
                $this->success(__('Intoed in successful'));
            }else if($row['states']==0){
                //还未预约
                $this->error(__('Please make an appointment before entering'));
            }else{
                //已过期，重新预约
                $this->error(__('Appointment expired'));
            }
        }
    }

    /**
     * 离开图书馆
     *
     * @param string $username  账号
     * @param string $sid 学号
     * 释放预约名额 
     */     
    public function leave()
    {
        $this->assign('pageTitle','图书馆登记'); 
        $url = $this->request->request('url', '');        
        if ($this->request->isPost())
        {
            $username = $this->request->post('username');
            $sid = $this->request->post('sid'); 

            // $token = $this->request->post('__token__');
            
            // $rule = [
            //     'username'  => 'require|length:2,20',
            //     'sid'  => 'require|length:8,30',
            //     '__token__' => 'require|token',
            // ];

            // $msg = [
            //     'username.require'  => 'Username can not be empty',
            //     'username.length'   => 'Username must be 2 to 20 characters',
            //     'sid.require' => 'sid can not be empty',
            //     'sid.length'  => 'sid must be 8 to 30 characters',
            // ];
            // $data = [
            //     'username'  => $username,
            //     'sid'  => $sid,
            //     '__token__' => $token,
            // ];
    
            // $validate = new Validate($rule, $msg);
            // $result = $validate->check($data);
            // if (!$result) {
            //     $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            // }

            $where['nickname'] = $username;
            $where['sid'] = $sid;
            $where['leave_states']=0;//找还未离开的
            $row = \app\common\model\ReserveRecord::where($where)->find();
            if($row['into_states']==1){
                //处理离开状态，做记录。
                $params['leave_time']= time();
                $params['leave_states']=1;
                $params['states']=0;
                $row->save($params);

                //给reservesetting表 释放记录，加回去一条记录
                //释放预约数量
                $id = 1;
                $sult = \app\common\model\ReserveSetting::find($id);
                if($sult){
                    $finy = ($sult['reserved_number']+1);
                    if($finy<$sult['reserve_number']){
                        $sult -> reserved_number = $finy;
                    }else{
                        $sult -> reserved_number = $sult['reserve_number'];
                    }
                    $sult -> save();
                }
                $this->success(__('Leaved in successful'));
            }else{
                //找不到这条记录，提示错误
                $this->error(__('还未预约'));            
            } 
        } 
        //获取预约总数，剩余数量
        $id = 1;
        $row = ReserveSetting::get($id);
        $this->view->assign('row',$row);        
        $this->view->assign('url', $url);
        return $this->view->fetch(); 

    }    
}
